package com.xhd.base.session;

import java.util.ConcurrentModificationException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;

import com.xhd.base.log.Log;
import com.xhd.base.log.LogFactory;
import com.xhd.cache.CacheMgr;
import com.xhd.cache.UseCache;
import com.xhd.exception.AuthorityException;
import com.xhd.exception.SessionException;
import com.xhd.exception.SystemException;
import com.xhd.server.Licence;
import com.xhd.server.ServerConfig;
import com.xhd.server.XMD5;
import com.xhd.util.XDate;

public class SessionManager implements UseCache {
	private Hashtable jm131 = null;
	private long jm132 = 0L;
	private long jm133 = 60000L;
	private static SessionManager jm16 = null;
	private int jm134 = 1;
	private String jm135 = null;
	private String jm84 = null;
	private SessionStore jm136 = null;
	private static final Log jm9;
	static Class jm10;

	static {
		Class tmp7_4 = jm10;
		if (tmp7_4 == null) {

			try {
				SessionManager.jm10 = Class
						.forName("com.sinocc.base.session.SessionManager");
			} catch (ClassNotFoundException localClassNotFoundException) {
				throw new NoClassDefFoundError(
						localClassNotFoundException.getMessage());
			}
		}
		jm9 = LogFactory.getLog(tmp7_4);
	}

	private SessionManager() {
		CacheMgr.registerCache(this);
		this.jm133 = (ServerConfig.RefreshSessionMinutes * 60000);
	}

	public static SessionManager getInstance() {
		if (jm16 == null)
			jm16 = new SessionManager();
		return jm16;
	}

	public Session getSessionById(String paramString) {
		if ((paramString == null) || (paramString.length() < 1))
			return null;
		Session localSession = (Session) this.jm131.get(paramString);
		if (localSession != null)
			return localSession;
		SessionId localCPCSessionId = new SessionId(paramString);
		if ((this.jm84 == null)
				|| (!(this.jm84.equals(localCPCSessionId.getServerId())))) {
			if (localCPCSessionId.getServerId() == null)
				return localSession;
			localSession = new Session();
			localSession.setId(paramString);
			if (getStore().load(localSession)) {
				this.jm131.put(paramString, localSession);
				jm9.debug("load session " + paramString + " OK.");
			} else {
				jm9.debug("load session " + paramString + " error.");
			}
		}
		return localSession;
	}

	public Session getSession(String paramString, long paramLong) {
		Session localSession = getSessionById(paramString);
		if ((localSession != null) && (paramLong > 0L)
				&& (paramLong != localSession.getTimestamp()))
			getStore().load(localSession);
		return localSession;
	}

	public Session newSession(int paramInt, String paramString)
			throws AuthorityException {
		String str = Licence.getLicence();
		if (str != null)
			str = str + paramString;
		else
			str = paramString;
		SessionId localCPCSessionId = new SessionId();
		localCPCSessionId.generateId(this.jm84, ServerConfig.CompanyId, str);
		Session localSession = new Session();
		localSession.setId(localCPCSessionId.getId());
		localSession.setGroupId(paramInt);
		return localSession;
	}

	public synchronized void loadSessions(String paramString1, int paramInt,
			String paramString2) throws SystemException {
		if ((paramString1 != null) && (paramString1.length() > 0))
			this.jm84 = paramString1;
		this.jm134 = paramInt;
		this.jm135 = paramString2;
		Hashtable localHashtable = getStore().loadAll();
		if (localHashtable != null)
			this.jm131.putAll(localHashtable);
		this.jm132 = System.currentTimeMillis();
		jm9.trace("Session count: " + this.jm131.size());
	}

	protected SessionStore getStore() {
		if (this.jm136 == null)
			if (this.jm134 == 1)
				this.jm136 = new SessionFileStore(this.jm84, this.jm135);
			else if (this.jm134 == 2)
				this.jm136 = new SessionFileStore(this.jm84, this.jm135);
		return this.jm136;
	}

	public void refreshSessionDatas(Vector paramVector) {
		removeAllSession();
		if ((paramVector == null) || (paramVector.size() < 1))
			return;
		for (int i = 0; i < paramVector.size(); ++i)
			try {
				Session localSession = new Session(
						(Hashtable) paramVector.get(i));
				jm127(localSession);
			} catch (Exception localException) {
				localException.printStackTrace();
			}
	}

	public void addSession(Session paramSession) throws SessionException {
		jm127(paramSession);
	}

	private void jm127(Session paramSession) throws SessionException {
		int i = 0;
		if (jm49())
			i = (cpc1(ServerConfig.SystemName, ServerConfig.CompanyId,
					ServerConfig.Licence, ServerConfig.LicenceDueDate) != 1) ? 1
					: 0;
		else
			i = (jm130(ServerConfig.SystemName, ServerConfig.CompanyId,
					ServerConfig.Licence, ServerConfig.LicenceDueDate) != 1) ? 1
					: 0;
		if (i != 0) {
			System.out.println("Invalid licence or time out!");
			System.exit(0);
		}
		if ((paramSession == null) || (!(paramSession.isValid())))
			throw new SessionException(80014);
		if (this.jm131.containsKey(paramSession.getId())) {
			if (ServerConfig.ServerType == 2)
				return;
			throw new SessionException(80015, paramSession.getId());
		}
		this.jm131.put(paramSession.getId(), paramSession);
		if (((ServerConfig.ServerType != 0) && (ServerConfig.ServerType != 1))
				|| (getStore().save(paramSession, true)))
			return;
		jm9.error("Save session failed: " + paramSession.getId());
	}

	public void flashActionTime(Vector paramVector) {
		if ((paramVector == null) || (paramVector.size() <= 0))
			return;
		for (int i = 0; i < paramVector.size(); ++i) {
			Vector localVector = (Vector) paramVector.elementAt(i);
			if (localVector == null)
				continue;
			String str = (String) localVector.elementAt(0);
			Session localSession = getSessionById(str);
			if (localSession == null)
				continue;
			localSession.flashAction(((Long) localVector.elementAt(1))
					.longValue());
		}
	}

	public void flashCheckMsg(Vector paramVector) {
		if ((paramVector == null) || (paramVector.size() <= 0))
			return;
		jm9.trace("Flash check message time ...");
		for (int i = 0; i < paramVector.size(); ++i) {
			Vector localVector = (Vector) paramVector.elementAt(i);
			if (localVector == null)
				continue;
			String str = (String) localVector.elementAt(0);
			Session localSession = getSessionById(str);
			if (localSession == null)
				continue;
			localSession.flashCheckMsg(((Long) localVector.elementAt(1))
					.longValue());
		}
		jm9.trace("Flash check message time OK");
	}

	public Vector getLoginUsers() {
		jm9.info("Session count: " + this.jm131.size());
		return jm128(false, false, 0);
	}

	public Vector getOnlineUsers(int paramInt) {
		return jm128(true, false, paramInt);
	}

	public Vector getOnlineUsers(boolean paramBoolean, int paramInt) {
		return jm128(true, paramBoolean, paramInt);
	}

	public Vector getUserOnline(int paramInt) {
		if (paramInt == 0)
			return null;
		int i = this.jm131.size();
		if (i < 1)
			return null;
		Vector localVector1 = new Vector();
		Vector localVector2 = new Vector(i);
		localVector2.addAll(this.jm131.values());
		for (int j = 0; j < i; ++j) {
			Session localSession = (Session) localVector2.get(j);
			if ((!(localSession.isValid())) || (!(localSession.isOnline()))
					|| (paramInt != localSession.getUserInfo().getSysUserId()))
				continue;
			localVector1.add(localSession);
		}
		localVector2.clear();
		localVector2 = null;
		return localVector1;
	}

	private Vector jm128(boolean paramBoolean1, boolean paramBoolean2,
			int paramInt) {
		if ((this.jm84 == null) && (this.jm133 > 0L)
				&& (System.currentTimeMillis() - this.jm132 > this.jm133)) {
			try {
				Hashtable localHashtable = getStore().loadAll();
				Hashtable localObject = this.jm131;
				this.jm131 = new Hashtable();
				if (localHashtable != null) {
					this.jm131.putAll(localHashtable);
					Iterator localIterator = ((Hashtable) localObject).values()
							.iterator();
					while (localIterator.hasNext()) {
						Session localSession1 = (Session) localIterator
								.next();
						Session localSession3 = (Session) this.jm131
								.get(localSession1.getId());
						if (localSession3 == null)
							continue;
						localSession3
								.flashAction(localSession1.getActionTime());
					}
				}
				((Hashtable) localObject).clear();
				localObject = null;
			} catch (SystemException localSystemException) {
				jm9.error(localSystemException);
			}
			this.jm132 = System.currentTimeMillis();
			jm9.trace("Refresh session.");
		}
		int i = this.jm131.size();
		if (i < 1)
			return null;
		Object localObject = new Vector(i);
		int j = 0;
		while (j < 5)
			try {
				((Vector) localObject).addAll(this.jm131.values());
			} catch (ConcurrentModificationException localConcurrentModificationException) {
				++j;
			}
		i = ((Vector) localObject).size();
		for (j = i - 1; j >= 0; --j) {
			Session localSession2 = (Session) ((Vector) localObject)
					.get(j);
			if ((localSession2.isValid())
					&& (((!(paramBoolean1)) || (localSession2.isOnline())))
					&& (((!(paramBoolean2)) || (localSession2.isLocal())))
					&& (((paramInt == 0) || (paramInt == localSession2
							.getGroupId()))))
				continue;
			((Vector) localObject).remove(j);
		}
		return ((Vector) localObject);
	}

	public boolean isUserOnline(int paramInt) {
		if (paramInt == 0)
			return false;
		Iterator localIterator = this.jm131.values().iterator();
		while (localIterator.hasNext()) {
			Session localSession = (Session) localIterator.next();
			if (!(localSession.isOnline()))
				continue;
			SessionUserInfo localSessionUserInfo = localSession.getUserInfo();
			if (paramInt == localSessionUserInfo.getSysUserId())
				return true;
		}
		return false;
	}

	public void removeAllSession() {
		this.jm131.clear();
	}

	public void removeSession(String paramString) {
		jm129(paramString);
	}

	private boolean jm129(String paramString) {
		if (paramString == null)
			return false;
		Session localSession = (Session) this.jm131.get(paramString);
		if (localSession == null)
			return false;
		if ((ServerConfig.ServerType == 0) || (ServerConfig.ServerType == 1)) {
			SessionId localCPCSessionId = new SessionId(paramString);
			Licence.freeLicence(localCPCSessionId.getLicence());
			this.jm131.remove(paramString);
			getStore().remove(paramString);
		} else {
			this.jm131.remove(paramString);
		}
		localSession.invalid();
		localSession = null;
		return true;
	}

	public void removeSession(Session paramSession) {
		if (paramSession == null)
			return;
		if (jm129(paramSession.getId()))
			return;
		paramSession.invalid();
	}

	public void storeSession(Session paramSession) {
		if (paramSession == null)
			return;
		getStore().save(paramSession);
	}

	public void storeSession(Session paramSession, boolean paramBoolean) {
		if (paramSession == null)
			return;
		paramSession.setTimestamp(System.currentTimeMillis());
		getStore().save(paramSession);
	}

	public void checkAll(long paramLong)
	  {
	    jm9.trace("Check session ...");
	    Vector localVector = new Vector(this.jm131.values());
	    int i = localVector.size();
	    for (int j = 0; j < i; ++j)
	    {
	    	Session localSession = (Session)localVector.get(j);
	      if (localSession.isValid())
	        continue;
	      try
	      {
	        String str = localSession.getId();
	        if (str == null)
	        {
	          str = (String)localSession.getAttribute("oldsessionid");
	          if (str != null)
	          {
	            this.jm131.remove(str);
	           // break label121:
	          }
	        }
	        label121: removeSession(str);
	      }
	      catch (Exception localException)
	      {
	        jm9.error(localException);
	      }
	    }
	    jm9.trace("Check session OK.");
	  }

	private native int cpc1(String paramString1, String paramString2,
			String paramString3, String paramString4);

	private int jm130(String paramString1, String paramString2,
			String paramString3, String paramString4) {
		XDate localDate = new XDate();
		if (localDate.toText1().compareTo(paramString4) >= 0)
			return 0;
		StringBuffer localStringBuffer = new StringBuffer(128);
		localStringBuffer.append(paramString1);
		localStringBuffer.append(":");
		localStringBuffer.append(paramString2);
		localStringBuffer.append(":");
		localStringBuffer.append(paramString4);
		XMD5 localCPCMD5 = new XMD5();
		if (paramString3.equals(localCPCMD5.getMD5(localStringBuffer.toString()
				.getBytes())))
			return 1;
		return 0;
	}

	private boolean jm49() {
		return ServerConfig.OsName.startsWith("window");
	}

	public boolean setOnline(String paramString, boolean paramBoolean) {
		Session localSession = getSessionById(paramString);
		if (localSession != null) {
			boolean bool = paramBoolean ^ localSession.isOnline();
			localSession.setOnline(paramBoolean);
			if (bool)
				getStore().saveAttributes(localSession, "isonline,msgserverid");
			return bool;
		}
		return false;
	}

	public boolean clearCache() {
		return false;
	}

	public int cacheSize() {
		return this.jm131.size();
	}

	public Object cacheData() {
		return this.jm131;
	}

	public void refreshSessionsById(String paramString) {
		if (paramString == null)
			return;
		Session localSession = (Session) this.jm131.get(paramString);
		if (localSession == null)
			return;
		getStore().load(localSession);
	}

	public void refreshSessionsById(Vector paramVector) {
		if ((paramVector == null) || (paramVector.size() < 1))
			return;
		int i = paramVector.size();
		SessionStore localSessionStore = getStore();
		for (int j = 0; j < i; ++j) {
			String str = (String) paramVector.elementAt(j);
			if (str == null)
				continue;
			Session localSession = (Session) this.jm131.get(str);
			if (localSession == null)
				continue;
			localSessionStore.load(localSession);
		}
	}
}
